<template>
  <div class="bannerImage">
    <ul>
      <li
        v-for="(item, index) in banner"
        :key="item"
        :class="['img', { active: activeImg === index }]"
      >
        <img class="imgs" ref="img" src="" :data-img="item" />
      </li>
    </ul>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data () {
    return {
      // 显示哪一张背景图片的索引
      activeImg: 0,
      // 用来关闭定时器
      timer: null,
      flag: true,
      n: 0
    }
  },
  computed: {
    // 背景图片的img数据
    ...mapState([
      'banner'
    ])
  },
  mounted () {
    if (this.flag) {
      this.setIntervalImage()
    }
    window.onscroll = this.lazyload()
  },
  methods: {
    lazyload () {
      // let seeHeight = document.documentElement.clientHeight // 可见区域高度
      // let scrollTop = document.documentElement.scrollTop || document.body.scrollTop // 滚动条距离顶部高度
      for (let i = this.n; i < this.banner.length; i++) {
        // 图片未出现时距离顶部的距离大于滚动条距顶部的距离+可视区的高度
        if (this.$refs.img[i].offsetTop === 0) {
          if (this.$refs.img[i].getAttribute('src') === '') {
            this.$refs.img[i].src = this.$refs.img[i].getAttribute('data-img')
          }
          this.n = i + 1
        }
      }
    },
    // 设置背景轮播
    setIntervalImage () {
      this.flag = false
      // 开启定时器
      this.timer = setInterval(() => {
        // 索引加一
        this.activeImg++
        // 判断索引是否或等于大于图片的总长
        if (this.activeImg >= this.banner.length) {
          // 如果等于总长设置为0重新轮播
          this.activeImg = 0
        }
      }, 6000)
    },
    clearIntervalImage () {
      clearInterval(this.timer)
    }
  }
}
</script>

<style lang="less" scoped>
.bannerImage {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  z-index: -1;
  .img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    transition: opacity 2s;
    img {
      position:absolute;
      top:0;
      bottom:0;
      left:50%;
      right:0;
      transform: translateX(-50%);
      height:100%;
      width: 100%;
      min-width: 1000px;
      z-index: -1;
      *zoom:1;
    }
    &.active {
      opacity: 1;
      animation: imagcacle 5s linear 1s;
    }
  }
}
@keyframes imagcacle {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}
</style>
